package com.lcz.mytest.activity;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.google.gson.Gson;
import com.lcz.mytest.R;
import com.lcz.mytest.widget.CustomProgressDialog;
import com.lcz.mytest.widget.ToolBarActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/4/21.
 */
public class PastStockChartActivity2 extends ToolBarActivity {
    private CustomProgressDialog loading_dialog;//加载提示
    private WebView webView;
    private SQLiteDatabase db;

    @Override
    protected void findViewById() {
        super.findViewById();
        setContentView(R.layout.activity_stockchart);
        webView = (WebView) findViewById(R.id.wv_showchar);
    }

    @Override
    protected void initView() {
        super.initView();
        getSupportActionBar().setTitle(getIntent().getStringExtra("name"));
        loading_dialog = new CustomProgressDialog(this, "加载中");
        copyDatabase();
        initWebView();
    }

    private void initWebView() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setUseWideViewPort(true);// 关键点

        // webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setLoadWithOverviewMode(true);
//        webSettings.setDisplayZoomControls(false);
        webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本
        webSettings.setAllowFileAccess(true); // 允许访问文件
        webSettings.setBuiltInZoomControls(false); // 设置显示缩放按钮
        webSettings.setSupportZoom(true); // 支持缩放

        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);// 滚动条风格，为0指滚动条不占用空间，直接覆盖在网页上
        //设置web视图
        webView.setWebChromeClient(new WebChromeClient());
        //加载页面
        webView.loadUrl("file:///android_asset/echart/tmp.html");
        showchart();
    }

    public void showchart() {
        //股票代码
        final String code = getIntent().getStringExtra("symbol");
        final Gson gson = new Gson();
        //时间
        final List<String> timeList = new ArrayList<String>();
        //数据集合
        final List<Double> data = new ArrayList<Double>();
        final List<List<Double>> dataList = new ArrayList<>();
        //均价集合
        final List<Double> avergeList = new ArrayList<Double>();
        final List<Double> aveList = new ArrayList<Double>();
        //收盘价
        final List<Double> closeList = new ArrayList<Double>();
        new AsyncTask<String, Integer, String>() {
            protected void onPreExecute() {
                loading_dialog.show();
            }

            @Override
            protected String doInBackground(String... params) {
                String code = params[0];
                if (db == null) {
                    db = SQLiteDatabase.openOrCreateDatabase(
                            getDatabasePath("stock").getAbsolutePath(), null);
                }
                // 查询
//                db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
                Cursor cursor = db.query("stock_daydata", null, "code = '"
                        + code + "'", null, null, null, "date");

                while (cursor.moveToNext()) {
                    // 拼接时间数组
                    String time = cursor.getString(cursor
                            .getColumnIndex("date"));
                    timeList.add(time);

                    double open = cursor.getDouble(cursor
                            .getColumnIndex("open"));
                    double close = cursor.getDouble(cursor
                            .getColumnIndex("close"));
                    double low = cursor.getDouble(cursor.getColumnIndex("low"));
                    double high = cursor.getDouble(cursor
                            .getColumnIndex("high"));

                    data.add(open);
                    data.add(close);
                    data.add(low);
                    data.add(high);
                    dataList.add(data);

//                    double average = cursor.getDouble(cursor.getColumnIndex("average"));
                    aveList.add(close);
                }

             /*将某一时间段的收盘股价或收盘指数相加的总和，除以时间周期，即得到这一时间的平均线。
                 *如5日移动平均线，就是将近5日的收盘价相加除以5，得到的就是第一个5日平均线的
                 *值 ，再将第一个5日平均线乘以5减去第一日的收盘价加上第6日的收盘价，其总和除以5得到 的就是第二个5日平均线值，
                 *将计算得到的平均数画在坐标图上连成线，即是5日平均线。
                * */
                for (int i = 0; i < aveList.size(); i++) {
                    double averageCount = 0;
                    closeList.add(aveList.get(i));
                    if (i >= 6) {
                        if (i > 6)
                            closeList.remove(0);
                        //保留小数
                        java.text.DecimalFormat myformat = new java.text.DecimalFormat("0.00");
                        averageCount = setAvege(closeList);
                        avergeList.add(Double.parseDouble(myformat.format(averageCount)));
                    } else {
                        averageCount = aveList.get(i);
                        avergeList.add(averageCount);
                    }
                }

                return null;
            }

            protected void onPostExecute(String result) {
                List<String> legendData = new ArrayList<String>();
                legendData.add(code);
                legendData.add("均价");
                webView.loadUrl("javascript:createKCharts(" + gson.toJson(code) + "," + gson.toJson(legendData) + "," + gson.toJson(timeList) + "," + gson.toJson(dataList) + "," + gson.toJson(avergeList) + ");");
                loading_dialog.dismiss();

            }
        }.execute(code);
    }

    private double setAvege(List<Double> list) {
        if (list == null || list.size() == 0) {
            return 0.00;
        }
        int total = 0;
        for (Double ave : list) {
            total += ave;
        }
        return total * 1f / list.size();
    }

    private void copyDatabase() {
        // 获取数据库文件
        final File file = getDatabasePath("stock");
        new AsyncTask<String, Integer, String>() {
            protected void onPreExecute() {
                loading_dialog.show();
            }

            @Override
            protected String doInBackground(String... params) {
                if (!file.exists()) {
                    try {
                        InputStream is = getAssets().open("stock");
                        if (!file.getParentFile().exists()) {
                            file.getParentFile().mkdirs();
                        }
                        file.createNewFile();
                        FileOutputStream fos = new FileOutputStream(file);
                        byte[] bys = new byte[1024];
                        int len;
                        while ((len = is.read(bys)) != -1) {
                            fos.write(bys, 0, len);
                        }
                        is.close();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }

            protected void onPostExecute(String result) {
                loading_dialog.dismiss();
            }
        }.execute();
    }
}
